class Trigger < ActiveRecord::Base
	belongs_to :user
	belongs_to :stock
	validates_presence_of :quantity
	validates_numericality_of :quantity, :price
	def self.filter (stock_id, action)
	  if action == "sell"
	  	find(:all,
	       :conditions 	=> "action = '#{action}' AND stock_id = '#{stock_id}'",
	       :order 		=> "price asc, created_at asc")
	  else
	  	find(:all,
	       :conditions 	=> "action = '#{action}' AND stock_id = '#{stock_id}'",
	       :order 		=> "price desc, created_at asc")
	  end
	  
	end
	
	def self.pop (stock_id, action)
	  if action == "sell"
	  	first(	:conditions 	=> "action = '#{action}' AND stock_id = '#{stock_id}'",
	       		:order 		=> "price asc, created_at asc")
	  else
	  	first(  :conditions 	=> "action = '#{action}' AND stock_id = '#{stock_id}'",
	       		:order 		=> "price desc, created_at asc")
	  end
	  
	end
	protected
	def validate
	  errors.add(:quantity, "should be positive") unless quantity.nil? || quantity > 0.0
	  errors.add(:price, "should be positive") unless price.nil? || price > 0.0
	end
end
